<template>
  <div class="ui-chart" :style="style">
    <div ref="control" class="ui-chart__control"></div>
    <div v-if="!ready" class="ui-chart__loading">
      <ui-loading :visible="true"></ui-loading>
    </div>
    <slot></slot>
  </div>
</template>
<script>
import * as echarts from 'echarts'
import Loading from '../loading'

export default {
  name: 'UiChart',
  components: {
    UiLoading: Loading
  },
  provide() {
    return {
      UiChart: this
    }
  },
  props: {
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '100%'
    },
    config: {
      type: Object
    }
  },
  data() {
    return {
      ready: false,
      series: [],
      options: null
    }
  },
  computed: {
    style() {
      return {
        width: this.width,
        height: this.height
      }
    }
  },
  created () {
    this.setOption(this.config)
  },
  mounted() {
    this.chart = echarts.init(this.$refs.control)
    this.chart.setOption(this.options)
    this.chart.on('click', (evt) => {
      this.$emit('click', evt)
    })
    this.ready = true
  },
  methods: {
    setOption (name, value) {
      let options = this.options || {}
      if (typeof name === 'string') {
        this.$set(options, name, value)
      } else if (typeof name == 'object') {
        options = Object.assign({}, options, name)
      }
      this.options = options
      if (this.chart) {
        this.chart.setOption(this.options)
      }
    },
    addSeries(series) {
      if (!series || !series.id) {
        return
      }
      if (this.series.some(v => v.id === series.id)) {
        return
      }
      const nextSeries = Object.assign({}, series)
      this.$emit('add-series', {
        series: nextSeries
      })
      this.series.push(nextSeries)
      this.setOption('series', this.series)
    },
    updateSeries(id, series) {
      const index = this.getSeriesIndex(id)
      if (index < 0) {
        return
      }
      const nextSeries = Object.assign({}, this.series[index], series)
      this.$emit('edit-series', {
        series: nextSeries
      })
      this.series.splice(index, 1, nextSeries)
      this.setOption('series', this.series)
    },
    removeSeries(id) {
      const index = this.getSeriesIndex(id)
      if (index < 0) {
        return
      }
      this.series.splice(index, 1)
      this.setOption('series', this.series)
    },
    getSeriesIndex(id) {
      let index = -1
      this.series.some((v, i) => {
        if (v.id === id) {
          index = i
          return true
        }
      })
      return index
    },
    doLayout() {
      if (!this.chart) {
        return
      }
      this.chart.resize && this.chart.resize()
    }
  }
}
</script>
<style lang="less">
.ui-chart{
  position: relative;
}
.ui-chart__control{
  width: 100%;
  height: 100%;
  overflow: hidden;
}
.ui-chart__loading{
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  z-index: 100;
}
</style>
